package com.zzj.ecology.framework.configs.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

@Component("accessDecisionManager")
public class CustomizeAccessDecisionManager implements AccessDecisionManager {

    private static final Logger logger = LoggerFactory.getLogger(CustomizeAccessDecisionManager.class);

    /*
     * public void com.zeng.boot.web.security.MyAccessDecisionManager.
     * decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttribute)
     * 		throws AccessDeniedException, InsufficientAuthenticationException
     *
     * decide() 方法是判断是否拥有权限的决策方法,三个参数
     * (1)Authentication authentication：表示 com.zeng.boot.web.security.CustomUserService 中循环添加到 GrantedAuthority对象中角色信息集合
     * (2)Object object：表示包含客户端发起的请求的requset信息,可转换为
     * 		HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
     * (3)Collection<ConfigAttribute> configAttribute：表示 MyFilterInvocationSecurityMetadataSourceService 的 getAttributes(Object object) 这个方法返回的结果.
     * 		此方法是为了判定用户请求的url是否在权限表中,如果在权限表中,则返回给 decide 方法,用来判定用户是否有此权限。
     * 		如果不在权限表中则放行。
     * */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttribute)
            throws AccessDeniedException, InsufficientAuthenticationException {

        if (configAttribute == null || configAttribute.size() <= 0) {//直接放行（此URL对应的角色configAttribute集合中无内容，内直接放行）
            return;
        }

        ConfigAttribute next = null;
        Iterator<ConfigAttribute> iters = configAttribute.iterator();
        while (iters.hasNext()) {
            next = iters.next();
            String attribute = next.getAttribute();
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                if (attribute.trim().equals(grantedAuthority.getAuthority())) {
                    return;
                }
            }
        }
        logger.info("zzj[=NG=] ===== CustomAccessDecisionManager decide()没有权限: {}");
        throw new AccessDeniedException("没有权限");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
